<template>
  <div>{{denglu}}</div>
</template>
<script>
import Qs from 'qs';

const { config } = window;

export default {
  layout: 'index_default', // 加载跳转页面模板
  data() {
    return {
      ts: this.newStore(),
      denglu: '未登录',

    };
  },
  created() {

  },
  mounted() {
    const query = Qs.parse(window.location.search.substring(1));
    // eslint-disable-next-line prefer-destructuring
    const code = query.code;

    if (config.MODE == 'dev') {
      this.getUserInfoByDev();
    } else {
      if (code && code != '') { // 从微信转回，进行服务器登录
        this.doLogin(code);
        return;
      }

      // 判断登录
      if (!this.checkLogin()) {
        this.getWxCode();
      } else {
        console.info('已经登录');
        // 进入index.0
        this.$router.push('/index.0');
      }
    }
  },
  methods: {
    // 判断登录
    checkLogin() {
      console.info('checkLogin');
      const rybToken = localStorage.getItem(`RYBTOKEN${config.LT}`);

      if (rybToken == null || rybToken == '') {
        return false;
      }

      const userInfoString = localStorage.getItem('userInfo');
      const hosInfoString = localStorage.getItem('hosInfo');

      if (userInfoString && userInfoString != '') {
        this.userInfo = JSON.parse(userInfoString);
      }
      if (hosInfoString && hosInfoString != '') {
        this.hosInfo = JSON.parse(hosInfoString);
      }

      return true;
    },

    // 执行登录
    getWxCode() {
      const wxLoginUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${config.hosInfo.APPID}&redirect_uri=${encodeURI(encodeURI(config.hosInfo.SERVER_URL))}&response_type=code&scope=snsapi_base&state=htyy#wechat_redirect`;
      // 改成ajax试试
      window.location = wxLoginUrl;

      // console.info("wxLoginUrl:"+wxLoginUrl);
      // this.spost(this.ts, wxLoginUrl).then((response) => {
      //  console.info(response);
      // });
    },

    doLogin(code) {
      console.info(`code = ${code}`);
      const loginUrl = `https://zyext.kejizhongyi.com/LoginServlet?reqType=wxmplogin&lt=${config.LT}&sid=${config.hosInfo.SID}&code=${code}`;

      this.spost(this.ts, loginUrl).then((response) => {
        console.info(response.d);
        if (response.d.errCode && response.d.errCode == '509') { // 未注册
          localStorage.setItem('openid', response.d.errMessage); // errMessage存放openid
          this.$router.push('login');
          return;
        }
        if (response.d.rybToken) {
          localStorage.setItem(`RYBTOKEN.${config.LT}`, response.d.rybToken);

          const userInfo = response.d.rybData;

          if (userInfo) {
            localStorage.setItem(`userInfo.${config.LT}`, JSON.stringify(userInfo));
          }

          console.info('登录成功');
          this.$router.push('/index.0');
        }
      });
    },
    getHospitalInfoDev() {
      let url = '';

      url = `/doctor/WeixinLogin.lg?reqType=OBTAIN&RYBID=${config.APIAPPID}&DATA=${config.APIRootDevDomainName}`;

      this.spost(this.ts, url)
        .then((response) => {
          if (response.d.RESULT == '514' || response.d.RESULT == '515' || response.d.RESULT == '516') {
            this.$messagebox('提示', `${response.d.RESULTTEXT}`);
          }
          sessionStorage.setItem('hosName', `${response.d.hosName}`);
          sessionStorage.setItem('APPID', `${response.d.APPID}`);

          console.log(`---------- 医院名称: ${sessionStorage.getItem('hosName')}`);
          console.log(`---------- 医院APPID: ${sessionStorage.getItem('APPID')}`);

          this.hospitalName = `${response.d.hosName}`;
          if (sessionStorage.getItem('rybToken') == '' || sessionStorage.getItem('rybToken') == null) {
            if (sessionStorage.getItem('APPID') != null && sessionStorage.getItem('APPID') != undefined && sessionStorage.getItem('APPID') != '') {
              this.getUserInfoByDev();
            } else {
              this.$messagebox('登录提示', '网络错误请刷新重试');
            }
          } else {
            this.$router.push('index.0');
          }
        }).catch((err) => {
          console.log(JSON.stringify(err));

          console.log('===============================22222222222222222222222222222222222222');
        // window.location.href = `http://${this.hospitalDomain}/medicys/error`;
        });
    },

    getUserInfoByDev() { /* 本地调试登录 */
      // let alert(code);
      const res = {
        RYBID: 'DOCTOR',
      };
      this.spost(this.ts, `${config.APIRootDev}/doctor/LocalDevLogin.dev`, res).then((response) => {
        console.log(JSON.stringify(response));
        if (response.d.RESULT == '514' || response.d.RESULT == '515' || response.d.RESULT == '516') {
          this.$messagebox('登录失败', `${response.d.RESULTTEXT}`);
          return;
        }
        // 跳转到注册页
        if (response.d.errCode == '513') {
          this.$router.push('/login');
          return;
        }
        if (response.d.rybToken) {
          localStorage.setItem(`RYBTOKEN.${config.LT}`, response.d.rybToken);

          const userInfo = response.d.rybData;

          if (userInfo) {
            localStorage.setItem(`userInfo.${config.LT}`, JSON.stringify(userInfo));
          }
        }

        this.$router.push('index.0');
      }).catch((err) => {
        sessionStorage.setItem('error', JSON.stringify(err));
      });
    },
  },
};
</script>
